/*
 * @Author: wei_jt@ecidi.com
 * @Date: 2020-08-27 20:29:37
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-09-06 15:49:49
 * @Description: 路由加载
 */
import { setRoutes } from '@/router'
import { getRouter } from '@/api/user'
import { arrayToTree, treeToArray } from '@/utils/array'
import { uuid, isJSON } from '@/utils/util'
import store from '@/store'
import storage from '@/utils/storage'
import { useMainRoute } from '@/config'
import deepmerge from 'deepmerge'

import { router } from '@/modules/FormCenter/commonFormRoute'
import Vue from 'vue'

import { addWildcard, filterSubRoute, importComponent, addAlias } from './extra'

/**
 * @description: 加载本地路由，加载成功且至少加载了一条路由时返回true
 * @return Boolean
 */
const getLocalRoutes = async function () {
  let routes = []
  const reqs = require.context('@/modules', true, /route\.js$/, 'lazy')

  //根据路径载入route文件
  const analysis = async function (arr, reg) {
    for (let k = 0; k < reqs.keys().length; k++) {
      let dpath = reqs.keys()[k]
      if (reg.test(dpath)) {
        let getModule = () => import(`@/modules/${dpath.replace('./', '')}`)
        let cReq = await getModule()
        const md = deepmerge({ meta: { menuId: uuid(18) } }, cReq.default, { clone: true })
        arr ? arr.push(md) : arr = [md]
        let reg = new RegExp('^' + dpath.replace('/route.js', '') + '\/[a-zA-Z]+\/route\.js$')
        md.children || (md.children = [])
        await analysis(md.children, reg)
      }
    }
  }

  await analysis(routes, /^\.\/[a-zA-Z]+\/route\.js$/)

  routes = addWildcard(routes)

  //首页置顶
  routes.sort((v1, v2) => {
    return '/home' == v2.path ? 1 : -1
  })

  store.commit('SET_ROUTES', routes)
  setRoutes(routes)

  return routes.length > 0
}




/**
 * @description: 加载线上路由
 *               处于qiankun下的子应用，且设置为使用父应用传入的数据作为路由数据源
 *               
 */
const getUserRoutes = function () {
  return new Promise((resolve, reject) => {
    if (useMainRoute && Vue.prototype.$InQianKun && Vue.prototype.$fksMainStore) {
      return resolve(getOwnRoutes(Vue.prototype.$fksMainStore.state.routes))
    }
    getRouter().then(res => {
      return resolve(getOwnRoutes(res.data))
    }).catch((e) => {
      return resolve(getOwnRoutes())
    })

  })
}



/**
 * @description:  只保留路径与基础路径一致的节点
 */
const getOwnRoutes = function (routeList = []) {
  //parse处理
  let array = parseMenu(routeList)

  //排序，带有customApp的自定义应用往后排
  array.sort((v1, v2) => {
    if (v1.meta?.config?.indexOf('customApp') - v2.meta?.config?.indexOf('customApp') != 0) {
      return (v1.meta.config.indexOf('customApp') - v2.meta.config.indexOf('customApp'))
    }
    return isNaN(v1.sort) && isNaN(v2.sort) ? 0 : (isNaN(v2.sort) ? -v1.sort - 1 : isNaN(v1.sort) ? v2.sort + 1 : v1.sort - v2.sort)
  })

  //array由扁平数组转树结构
  try {
    array = treeToArray(array)
    array = arrayToTree(array, 'parentId')
  } catch (e) {
  }

  //自定义应用的过滤
  let routes = array.filter((a) => {
    return !a.meta.config.includes('customApp') || (a.children instanceof Array && a.children.length > 0)
  }) ?? []

  // 子应用模式下，根据节点筛选出自己的路由并处理
  routes = filterSubRoute(routes)

  routes = addWildcard(routes)

  store.commit('SET_ROUTES', routes)

  //component由string转为func，主应用模式下，不加载子应用的组件
  for (let i = 0; i < routes.length; i++) {
    importComponent(routes[i])
  }

  setRoutes(routes)

  return routes.length > 0
}

const parseMenu = function (menus) {
  const array = []
  const formTemp = []
  for (let i = 0; i < menus.length; i++) {
    try {
      //路由转换
      const menuItem = { ...menus[i] }
      menuItem.meta = isJSON(menuItem.meta) ? JSON.parse(menuItem.meta) : {}
      if (!menuItem.meta.config) {
        menuItem.meta.config = []
      }
      if (menuItem.meta?.config?.includes('disabled') || menuItem.enable === false) {
        continue
      }
      // menuItem.component = () => import(`@/modules${menus[i].component}`)
      menuItem.name = menuItem.code

      menuItem.meta.query || (menuItem.meta.query = {})

      if (menuItem.meta.query instanceof Array) {
        menuItem.meta.query = menuItem.meta.query.reduce((pval, val) => {
          pval[val.key] = val.value
          return pval
        }, {})
      }

      //链接携带token
      if (menuItem.meta?.config?.includes('token')) {
        Object.assign(menuItem.meta.query, { token: storage.get('access_token') })

      }

      //链接携带form
      if (menuItem.meta?.config?.includes('form')) {
        formTemp.push(...router(menuItem.path, menuItem.id))
      }

      //内嵌页面处理
      if (menuItem.meta.type == 'iframe') {
        Object.assign(menuItem.meta.query, { url: menuItem.path })
        menuItem.path = '/iframe/' + menuItem.id
        menuItem.component = '/Iframe/index.vue'
      }


      //1.8.3及之前版本后可兼容菜单显影

      // if (menuItem.hidden) {
      //   menuItem.meta.config instanceof Array ? (!menuItem.meta.config.includes('invisible') && menuItem.meta.config.push('invisible')) : menuItem.meta.config = ['invisible']
      // }

      menuItem.path || (menuItem.path = '')
      menuItem.meta.menuId = menuItem.id
      array.push(menuItem)
    } catch (error) {
      console.error(error)
    }
  }
  array.push(...formTemp)
  return array
}

export {
  getLocalRoutes,
  getUserRoutes,
  addAlias
}

